package com.chaoxing.scheduler;

import com.chaoxing.config.ChaoXingConfig;
import com.chaoxing.entity.Activity;
import com.chaoxing.entity.Course;
import com.chaoxing.entity.SignResult;
import com.chaoxing.entity.ChatGroup;
import com.chaoxing.service.ChaoXingService;
import com.chaoxing.service.NotificationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
@Component
public class SignScheduler {
    
    @Autowired
    private ChaoXingService chaoXingService;
    
    @Autowired
    private NotificationService notificationService;
    
    @Autowired
    private ChaoXingConfig config;
    
    private final AtomicBoolean isRunning = new AtomicBoolean(false);
    
    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady() {
        if (!config.getSign().isEnabled()) {
            log.info("自动签到功能已禁用");
            return;
        }
        
        log.info("学习通自动签到系统已启动");
        log.info("用户名: {}", config.getUsername());
        log.info("检查间隔: {}ms", config.getSign().getCheckInterval());
        
        // 启动时立即执行一次
        performSignCheck();
    }
    
    @Scheduled(fixedDelayString = "${chaoxing.sign.check-interval:300000}")
    public void scheduledSignCheck() {
        if (!config.getSign().isEnabled()) {
            return;
        }
        
        performSignCheck();
    }
    
    private void performSignCheck() {
        if (isRunning.compareAndSet(false, true)) {
            try {
                log.debug("开始执行签到检查...");
                
                // 检查登录状态
                if (!chaoXingService.isLoggedIn()) {
                    log.info("用户未登录，正在尝试登录...");
                    if (!chaoXingService.login()) {
                        log.error("登录失败，跳过本次检查");
                        notificationService.sendNotification("学习通登录失败", 
                            "请检查用户名和密码是否正确");
                        return;
                    }
                }
                
                // 获取课程列表
                List<Course> courses = chaoXingService.getCourses();
                log.info("获取到 {} 门课程", courses.size());
                
                // 班级签到已集成在课程签到中，无需单独处理
                List<ChatGroup> chatGroups = new ArrayList<>();
                
                List<SignResult> signResults = new ArrayList<>();
                
                // 遍历每门课程
                for (Course course : courses) {
                    log.debug("检查课程: {}", course.getCourseName());
                    
                    // 获取活动列表
                    List<Activity> activities = chaoXingService.getActivities(course);
                    
                    // 执行签到
                    for (Activity activity : activities) {
                        if (activity.isActive() && !activity.isSigned()) {
                            log.info("发现待签到活动: {} - {}", 
                                course.getCourseName(), activity.getName());
                            
                            SignResult result = chaoXingService.doSign(activity, course);
                            result.setCourseName(course.getCourseName());
                            signResults.add(result);
                            
                            // 发送通知
                            if (result.isSuccess()) {
                                notificationService.sendNotification(
                                    "签到成功", 
                                    String.format("%s - %s", course.getCourseName(), activity.getName())
                                );
                            } else {
                                notificationService.sendNotification(
                                    "签到失败", 
                                    String.format("%s - %s: %s", 
                                        course.getCourseName(), activity.getName(), result.getMessage())
                                );
                            }
                        }
                    }
                }
                
                // 遍历每个群聊
                for (ChatGroup chatGroup : chatGroups) {
                    log.debug("检查群聊: {}", chatGroup.getChatId());
                    
                    // 获取班级签到活动
                    List<Activity> chatActivities = chaoXingService.getChatGroupActivities(chatGroup);
                    
                    // 执行班级签到
                    for (Activity activity : chatActivities) {
                        if (activity.isActive() && !activity.isSigned()) {
                            log.info("发现班级签到活动: 群聊{} - {}", 
                                chatGroup.getChatId(), activity.getName());
                            
                            SignResult result = chaoXingService.doChatGroupSign(activity, chatGroup);
                            signResults.add(result);
                            
                            // 发送通知
                            if (result.isSuccess()) {
                                notificationService.sendNotification(
                                    "班级签到成功", 
                                    String.format("群聊 - %s", activity.getName())
                                );
                            } else {
                                notificationService.sendNotification(
                                    "班级签到失败", 
                                    String.format("群聊 - %s: %s", 
                                        activity.getName(), result.getMessage())
                                );
                            }
                        }
                    }
                }
                
                if (signResults.isEmpty()) {
                    log.debug("本次检查未发现待签到的活动");
                } else {
                    log.info("本次检查完成，签到结果: {}", signResults);
                }
                
            } catch (Exception e) {
                log.error("签到检查异常", e);
                notificationService.sendNotification("签到检查异常", e.getMessage());
            } finally {
                isRunning.set(false);
            }
        } else {
            log.warn("上一次签到检查尚未完成，跳过本次检查");
        }
    }
}